/* eslint-disable  @typescript-eslint/no-explicit-any */

import axios, { AxiosError, AxiosResponse, InternalAxiosRequestConfig, AxiosRequestConfig } from 'axios';
import { ElMessage } from 'element-plus';

import { getMessageInfo } from './status';

export interface BaseResponse<T = any> {
    code: number | string;
    message: string;
    data: T;
    status?: number;
}

const service = axios.create({
    baseURL: import.meta.env.VITE_APP_DEV_USE_MOCK
        ? import.meta.env.VITE_APP_MOCK_BASEURL
        : import.meta.env.VITE_APP_API_BASEURL,
    timeout: 15000,
});

// 请求-拦截器
service.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        return config;
    },
    (error: AxiosError) => {
        return Promise.reject(error);
    },
);

// 响应-拦截器
service.interceptors.response.use(
    (response: AxiosResponse) => {
        if (response.status === 200) {
            return response;
        }
        ElMessage({
            message: getMessageInfo(response.status),
            type: 'error',
        });
        return response;
    },
    (err: any) => {
        const { response } = err;
        if (response) {
            ElMessage({
                message: getMessageInfo(response.status),
                type: 'error',
            });
            return Promise.reject(response.data);
        }
        ElMessage({
            message: '网络连接异常，请稍后再试!',
            type: 'error',
        });
    },
);

// 二次拦截，为响应数据定制化处理
export const requestInstance = <T = any>(config: AxiosRequestConfig): Promise<BaseResponse<T>> => {
    const conf = config;
    return new Promise((resolve, reject) => {
        service.request<any, AxiosResponse<BaseResponse>>(conf).then((res: AxiosResponse<BaseResponse>) => {
            const data = res.data;
            // 如果data.code为错误代码返回message信息
            if (data.code !== 0) {
                ElMessage({
                    message: data.message,
                    type: 'error',
                });
                reject(data.message);
            } else {
                ElMessage({
                    message: data.message,
                    type: 'success',
                });
                // 此处返回data信息 也就是 api 中配置好的 Response类型
                resolve(data as BaseResponse<T>);
            }
        });
    });
};

export default service;
